package com.zoweunion.mechanic.controller.api;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserUserinfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserUserinfoShareResponse;
import com.zoweunion.mechanic.config.AlipayConfig;
import com.zoweunion.mechanic.config.JVerifyConfig;
import com.zoweunion.mechanic.config.JpushConfig;
import com.zoweunion.mechanic.config.RabbitMQForLoginConfig;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.dao.base.UserDao;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.model.WxUserInfo;
import com.zoweunion.mechanic.plugins.mq.RabbitMQCustomer;
import com.zoweunion.mechanic.plugins.redis.RedisUtil;
import com.zoweunion.mechanic.plugins.shiro.JWTUtil;
import com.zoweunion.mechanic.service.app.SpeedyLoginService;
import com.zoweunion.mechanic.service.base.UserService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.gaode.AddressGEOUtil;
import httpsTrustClient.HTTPSTrustClient;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.HttpClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/speedy")
public class SpeedyLoginController extends BaseController{

    @Autowired
    private SpeedyLoginService speedyLoginService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private RabbitMQCustomer rabbitMQCustomer;
    @Autowired
    private AddressGEOUtil addressGEOUtil;
    @Autowired
    private UserDao userDao;
    @Autowired
    private RabbitMQForLoginConfig rmqlc;

    @Autowired
    private JVerifyConfig jVerifyConfig;

    @Autowired
    private JpushConfig jpushConfig;

    @PostMapping("alipayAuthInfoStr")
    public Object alipayAuthInfoStr(@RequestBody String str, HttpServletRequest request)
        throws Exception {

        try {

            Map <String,String > map = new HashMap<>();

            map.put("apiname","com.alipay.account.auth");
            map.put("method","alipay.open.auth.sdk.code.get");
            map.put("app_id", AlipayConfig.app_id);
            map.put("app_name","mc");
            map.put("biz_type","openservice");
            map.put("pid", AlipayConfig.pid);
            map.put("product_id","APP_FAST_LOGIN");
            map.put("scope","kuaijie");
            map.put("target_id", "201412251234");
            map.put("auth_type","AUTHACCOUNT");
            map.put("sign_type","RSA2");

            String signStr = AlipaySignature.getSignContent(map);
            String sign = AlipaySignature.rsaSign(signStr, AlipayConfig.merchant_private_key, "GBK");

            String encodeStr = URLEncoder.encode(map.toString(),"GBK");

            String infoStr = signStr + "&sign=" + URLEncoder.encode(sign,"GBK");

            Map<String,Object> paramap = new HashMap<>();

            paramap.put("infoStr", infoStr);

            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", paramap);

        } catch (Exception e) {

            return new ResponseBean(Constants.CODE_ERROR, "操作失败", null);
        }
    }

    @PostMapping("bindingAccount")
    public Object bindingAccount(@RequestBody String str, HttpServletRequest request)
        throws Exception {

        Map<String, Object> reqMap = JSONObject.parseObject(str,Map.class);

        User existUser = userService.getUserByAccount(reqMap.get("user_account").toString());

        if(existUser == null) {

            return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "该用户不存在",null);

        }

        if (!existUser.getUser_password().equals(MD5.md5(reqMap.get("user_password").toString()))){

            return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "用户名或密码错误", null);

        } else {

            //2.验证通过查询具体用户信息并返回
            Map<String, Object> userInfo = userService.getUserInfoByAccount(reqMap.get("user_account").toString());

            Optional<Map<String, Object>> optional = Optional.ofNullable(userInfo);

            if (optional.isPresent()) {

                Optional<Map<String, Object>> optional1 = optional.map((Map<String, Object> userInfoMap) -> {

                    //2.1生成JWTtoken
                    userInfoMap.put("Authorization", JWTUtil.sign(userInfoMap.get("user_account").toString(),userInfoMap.get("user_password").toString()));

                    userInfoMap.put("open_id",reqMap.get("open_id").toString());

                    return userInfoMap;
                });

                int result = speedyLoginService.updateOpenId(optional.get());

                if (result > 0) {

                    return new ResponseBean(Constants.CODE_SUCCESS, "登录成功",optional1.get());
                }else {

                    return new ResponseBean(Constants.CODE_ERROR, "绑定失败",optional1.get());
                }

            }else {

                return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "用户名或密码错误", null);
            }
        }
    }

    /**
     * 快捷登录
     * @Deprecated 2019-07-26 丢弃原因，使用新接口 /speedyLogin
     */
    @Deprecated
    @PostMapping("login")
    public Object speedyLogin(@RequestBody String str, HttpServletRequest request)
            throws Exception {

        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);

        JSONObject resultObj = new JSONObject();
        int code = Constants.CODE_ERROR;
        String message = "";

        try {

            switch (reqMap.get("type").toString()) {

                // 短信登录
                case "1":

                    User existUser = userService.getUserByAccount(reqMap.get("mobile_phone").toString());

                    if(existUser == null) {

                        Map<String,Object> backMap = new HashMap<>();

                        backMap.put("flag",false);

                        code = Constants.CODE_SUCCESS;
                        message = "该账号暂未注册";

                        resultObj.put("data",backMap);

                    } else {

                        //2.验证通过查询具体用户信息并返回
                        Map<String, Object> userInfo = userService.getUserInfoByAccount(reqMap.get("mobile_phone").toString());

                        Optional<Map<String, Object>> optional = Optional.ofNullable(userInfo);

                        if (optional.isPresent()) {

                            Optional<Map<String, Object>> optional1 = optional.map((Map<String, Object> userInfoMap) -> {

                                //2.1生成JWTtoken
                                userInfoMap.put("Authorization", JWTUtil.sign(userInfoMap.get("user_account").toString(),userInfoMap.get("user_password").toString()));

                                userInfoMap.put("flag",true);

                                return userInfoMap;
                            });

                            code = Constants.CODE_SUCCESS;
                            message = "短信登录成功";
                            resultObj.put("data",optional1.get());

                        }else {

                            return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "短信登录失败", null);
                        }
                    }

                    break;

                // 微信登录
                case "2":

                    HttpClient httpClient = null;;
                    httpClient = new HTTPSTrustClient().init();

                    Map<String, String> paramHeader = new HashMap<>();
                    paramHeader.put("Accept", "application/xml");

                    Map<String, String> paramBody = new HashMap<>();

                    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AlipayConfig.wechatAppid+"&secret="+AlipayConfig.appSecret+"&code="+reqMap.get("auth_code").toString()+"&grant_type=authorization_code";

                    String result = HTTPSClientUtil.doGet(httpClient,url,paramHeader,paramBody);

                    Map<String, Object> resultMap = JSONObject.parseObject(result, Map.class);

                    String getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+resultMap.get("access_token").toString()+"&openid="+resultMap.get("openid").toString()+"";

                    String userInfoStr = HTTPSClientUtil.doGet(httpClient,getUserInfoUrl,paramHeader,paramBody);

                    Map<String,Object> wechatMap = JSONObject.parseObject(userInfoStr,Map.class);

                    String openid = wechatMap.get("openid").toString();

                    Map<String,Object> wechatInfoMap = speedyLoginService.userInfoWithOpenId(openid);

                    wechatInfoMap.put("open_id",openid);

                    code = Constants.CODE_SUCCESS;

                    if (wechatInfoMap.get("flag").equals(false)) {

                        message = "该微信账号没有绑定任何账号";
                    }else {

                        message = "微信快捷登录成功";
                    }

                    resultObj.put("data",wechatInfoMap);

                    break;

                // 支付宝登录
                case "3":

                    AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.app_id, AlipayConfig.merchant_private_key,"json", "GBK", AlipayConfig.alipay_public_key, "RSA2");

                    // 通过app获取的auth_code 来获取accesstoken
                    AlipaySystemOauthTokenRequest tokenRequest = new AlipaySystemOauthTokenRequest();//创建API对应的request类

                    tokenRequest.setGrantType("authorization_code");
                    tokenRequest.setCode(reqMap.get("auth_code").toString());

                    AlipaySystemOauthTokenResponse tokenResponse = alipayClient.execute(tokenRequest);//通过alipayClient调用API，获得对应的response类

                    // 用access_token 获取用户信息
                    AlipayUserUserinfoShareRequest userinfoRequest = new AlipayUserUserinfoShareRequest();//创建API对应的request类
                    AlipayUserUserinfoShareResponse response = alipayClient.execute(userinfoRequest, tokenResponse.getAccessToken());//在请求方法中传入上一步获得的access_token

                    String userId = response.getUserId();

                    Map<String,Object> userInfoMap = speedyLoginService.userInfoWithOpenId(userId);

                    userInfoMap.put("open_id",userId);

                    code = Constants.CODE_SUCCESS;

                    if (userInfoMap.get("flag").equals(false)) {

                        message = "该支付宝账号没有绑定任何账号";
                    }else {

                        message = "支付宝快捷登录成功";
                    }

                    resultObj.put("data",userInfoMap);

                    break;
            }

        } catch (Exception e) {

            code = Constants.CODE_ERROR;
            message = "登录失败";
            logger.error(e.toString(), e);

        } finally {

            resultObj.put("code", code);
            resultObj.put("message", message);
            logAfter(logger);
        }

        return resultObj;
    }

    /**
     * 注销账号
     * @Deprecated 2022-05-26 接口/ logout
     */
    @PostMapping("logout")
    public ResponseBean logout(@RequestBody String str, HttpServletRequest request) throws MyException {
        String password = getCurrentUser(request).getUser_password();
        Map<String, Object> map = JSONObject.parseObject(str);
        Map<String, Object> maps =new HashMap<>();
        if (map.get("password") == null || StringUtils.isBlank(map.get("password").toString())) {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "请输入密码", false);
        }else{
            maps.put("user_account",getCurrentUser(request).getUser_account());
            maps.put("mobile_phone",getCurrentUser(request).getMobile_phone());
            maps.put("password",MD5.md5(String.valueOf(map.get("password"))));
        }
        if(MD5.md5(String.valueOf(map.get("password"))).equals(password)){
           boolean result = userService.logout(maps);
           if(result) {
               return new ResponseBean(Constants.CODE_SUCCESS, "注销成功！", true);
           }else{
               return new ResponseBean(Constants.CODE_ERROR,"注销失败！", false);
           }
        }else {
           return new ResponseBean(Constants.CODE_ERROR,"密码错误！", false);
        }
    }


    /**
     * 微信和支付吧授权登陆，绑定手机号
     * @param wxUserInfo
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("bindingMobilePhone")
    public Object bindingMobilePhone(@RequestBody WxUserInfo wxUserInfo, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(wxUserInfo.getOpenid()) || StringUtils.isBlank(wxUserInfo.getMobile_phone())) {
            return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "参数错误", null);
        }
        if (WxUserInfo.TYPE_WX.equals(wxUserInfo.getType())) {
            Map<String, Object> wechatInfoMap = speedyLoginService.userInfoWithWxId(wxUserInfo.getOpenid(), WxUserInfo.TYPE_WX);
            if (Boolean.valueOf(wechatInfoMap.get("flag").toString())) {
                return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "此微信号已经被绑定", null);
            }
            // 判断是否已经绑定过
            User user = userService.getUserByAccount(wxUserInfo.getMobile_phone());
            if (user != null) {
                if (StringUtils.isNotBlank(user.getOpen_id())) {
                    return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "此账号已绑定微信，如要更换请先解绑", null);
                } else {
                    userService.bindWxWrap(user, WxUserInfo.TYPE_WX, wxUserInfo.getOpenid());
                }
            } else {
                //2注册用户
                String userId = this.wrapRegister(wxUserInfo, "open_id");
                wxUserInfo.setUser_id(userId);
            }
            // 保存微信信息
            userService.saveWxUserInfo(wxUserInfo);
            // 返回授权信息
            return new ResponseBean(Constants.CODE_SUCCESS, "绑定成功", this.wrapResultMap(wxUserInfo, wxUserInfo.getMobile_phone()));
        } else if (WxUserInfo.TYPE_ALIPAY.equals(wxUserInfo.getType())) {
            Map<String, Object> userInfoMap = speedyLoginService.userInfoWithWxId(wxUserInfo.getOpenid(), WxUserInfo.TYPE_ALIPAY);
            if (Boolean.valueOf(userInfoMap.get("flag").toString())) {
                return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "此支付宝账号已经被绑定", null);
            }
            User user = userService.getUserByAccount(wxUserInfo.getMobile_phone());
            if (user != null) {
                if (StringUtils.isNotBlank(user.getAli_user_id())) {
                    return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "此账号已绑定支付宝，如要更换请先解绑", null);
                } else {
                    userService.bindWxWrap(user, WxUserInfo.TYPE_ALIPAY, wxUserInfo.getOpenid());
                }
            } else {
                //2注册用户
                String userId = this.wrapRegister(wxUserInfo, "ali_user_id");
                wxUserInfo.setUser_id(userId);
            }
            // 保存信息
            userService.saveWxUserInfo(wxUserInfo);
            // 返回授权信息
            return new ResponseBean(Constants.CODE_SUCCESS, "绑定成功", this.wrapResultMap(wxUserInfo, wxUserInfo.getMobile_phone()));
        } else {
            return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "不支持的绑定方式", null);
        }
    }

    private String wrapRegister (WxUserInfo wxUserInfo, String openidKey){
        //2注册用户
        Map<String, Object> userMap = new HashMap<>();
        // 用户账号
        userMap.put("mobile_phone", wxUserInfo.getMobile_phone());
        // 手机号中间部分设置为✳
        userMap.put("user_name", this.secretMobilePhone(wxUserInfo.getMobile_phone()));
        // 设置默认密码
        userMap.put("user_password", "123456");
        userMap.put(openidKey, wxUserInfo.getOpenid());
        userMap.put("sexy", wxUserInfo.getSex());
        // 创建账号
        return userService.doRegister(userMap);
    }


    /**
     * 快捷登陆
     * 1.手机号验证码登陆
     * 	- 新用户：账户不存在，创建账号，返回授权信息
     * 	- 老用户：账号已经存在，返回授权信息
     * 2.微信快捷登录
     * 	- 新用户：通过微信号查询账号，账号不存在，返回标识，app端跳出绑定手机号页面，进行绑定，更新账号名为手机号，绑定手机号成功之后，返回授权信息➕用户信息
     * 	- 老用户：通过微信号查询账号，账号存在，判断是否绑定过手机号，
     * 		~ 未绑定手机号，app端跳出绑定手机号页面，进行注册和绑定，绑定手机号成功之后，返回授权信息➕用户信息
     * 		~ 已绑定手机号，返回授权信息➕用户信息
     * 3.支付宝快捷登录 同微信登陆
     */
    @PostMapping("speedyLogin")
    public Object speedyLoginNew(@RequestBody String str, HttpServletRequest request) throws Exception {
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        JSONObject resultObj = new JSONObject();
        int code = Constants.CODE_ERROR;
        String message = "";
        WxUserInfo wxUserInfo;
        Map<String, Object> resultMap;
        try {
            switch (reqMap.get("type").toString()) {
                // 短信登录
                case "1":
                    String mobilePhone = reqMap.get("mobile_phone").toString();
                    User existUser = userService.getUserByAccount(mobilePhone);
                    // 用户不存在是为新用户
                    if (existUser == null) {
                        //2注册用户
                        Map<String, Object> userMap = new HashMap<>();
                        // 用户账号
                        userMap.put("mobile_phone", mobilePhone);
                        // 手机号中间部分设置为✳
                        userMap.put("user_name", this.secretMobilePhone(mobilePhone));
                        // 设置默认密码
                        userMap.put("user_password", "123456");
                        String userId = userService.doRegister(userMap);

                        // 新用户创建后，再执行登陆逻辑
                        Map<String, Object> newUserMap = userService.getUserInfoByAccount(mobilePhone);
                        if (newUserMap != null) {
                            newUserMap.put("Authorization", JWTUtil.signNotExpire(newUserMap.get("user_account").toString(), newUserMap.get("user_password").toString()));
                            newUserMap.put("flag", true);
                            newUserMap.put("bindingWxInfo", userService.myBindWx(newUserMap));
                            code = Constants.CODE_SUCCESS;
                            message = "手机一键登陆或短信登录成功";
                            Map<String,String> map = new HashMap<>();
                            map.put("user_account", newUserMap.get("user_account").toString());
                            Map<String,String> userInfo = userDao.getUser(map);
                            try {
                                this.sendMQMessage(userInfo.get("id"));
                            } catch(Exception e) {
                            } finally {
                                resultObj.put("data", newUserMap);
                            }
                        } else {
                            return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "手机一键登陆或短信登录失败", null);
                        }
                    } else {
                        //2.验证通过查询具体用户信息并返回
                        Map<String, Object> userMap = userService.getUserInfoByAccount(mobilePhone);
                        if (userMap != null) {
                            userMap.put("Authorization", JWTUtil.signNotExpire(userMap.get("user_account").toString(), userMap.get("user_password").toString()));
                            userMap.put("flag", true);
                            userMap.put("bindingWxInfo", userService.myBindWx(userMap));
                            code = Constants.CODE_SUCCESS;
                            message = "手机一键登陆或短信登录成功";
                            Map<String,String> map = new HashMap<>();
                            map.put("user_account",userMap.get("user_account").toString());
                            Map<String,String> userInfo = userDao.getUser(map);
                            try {
                                this.sendMQMessage(userInfo.get("id"));
                            }catch(Exception e){
                            }finally {
                                resultObj.put("data", userMap);
                            }
                        } else {
                            return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "手机一键登陆或短信登录失败", null);
                        }
                    }
                    break;
                // 微信登录
                case "2":
                    // 获取token信息
                    Map<String, Object> tokenInfoMap = ThirdPartyAuthUtil.getAccessTokenWX(reqMap.get("auth_code").toString());
                    if (tokenInfoMap.get("access_token") == null) {
                        return new ResponseBean(Constants.CODE_HANDEL_FAILED, "获取微信token失败", null);
                    }
                    // 获取微信用户信息
                    wxUserInfo = ThirdPartyAuthUtil.getUserInfoWX(tokenInfoMap.get("access_token").toString(), tokenInfoMap.get("openid").toString());
                    resultMap = speedyLoginService.userInfoWithWxId(wxUserInfo.getOpenid(), WxUserInfo.TYPE_WX);
                    resultMap.put("wxUserInfo", wxUserInfo);
                    code = Constants.CODE_SUCCESS;
                    if (resultMap.get("flag").equals(false)) {
                        message = "该微信账号没有绑定任何账号";
                    } else {
                        // 当再wxuserinfo表中查不到时，插入数据
                        wxUserInfo.setUser_id(resultMap.get("id").toString());
                        userService.saveNotFoundWx(wxUserInfo);
                        resultMap.put("bindingWxInfo", userService.myBindWx(resultMap));
                        message = "微信快捷登录成功";
                        try {
                            this.sendMQMessage(resultMap.get("id").toString());
                        } catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                    resultObj.put("data", resultMap);
                    break;
                // 支付宝登录
                case "3":
                    // 获取支付宝token信息
                    AlipaySystemOauthTokenResponse tokenResponse = ThirdPartyAuthUtil.getAccessTokenAlipay(reqMap.get("auth_code").toString());
                    // 获取支付宝用户信息
                    AlipayUserUserinfoShareResponse userInfoAlipay = ThirdPartyAuthUtil.getUserInfoAlipay(tokenResponse.getAccessToken());
                    // 支付宝信息的userid
                    String aliUserId = userInfoAlipay.getUserId();
                    resultMap = speedyLoginService.userInfoWithWxId(aliUserId, WxUserInfo.TYPE_ALIPAY);
                    wxUserInfo = ThirdPartyAuthUtil.alipayUserInfoToWxUserInfo(userInfoAlipay);
                    resultMap.put("wxUserInfo", wxUserInfo);
                    code = Constants.CODE_SUCCESS;
                    if (resultMap.get("flag").equals(false)) {
                        message = "该支付宝账号没有绑定任何账号";
                    } else {
                        // 当再wxuserinfo表中查不到时，插入数据
                        wxUserInfo.setUser_id(resultMap.get("id").toString());
                        userService.saveNotFoundWx(wxUserInfo);
                        resultMap.put("bindingWxInfo", userService.myBindWx(resultMap));
                        message = "支付宝快捷登录成功";
                        try {
                            this.sendMQMessage(resultMap.get("id").toString());
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                    resultObj.put("data", resultMap);
                    break;
                // 账号密码登陆
                case "4":
                    //1.验证用户名密码
                    Map<String, Object> reqUser = JSONObject.parseObject(str, Map.class);
                    if (StringUtils.isBlank(reqUser.get("mobile_phone").toString())) {
                        return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "请填写账号", null);
                    }
                    Map<String, Object> userMap = userService.getUserInfoByAccount(reqUser.get("mobile_phone").toString());
                    if (userMap == null) {
                        return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "该用户不存在", null);
                    }
                    if (!userMap.get("user_password").equals(MD5.md5(reqUser.get("user_password").toString()))) {
                        return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED, "用户名或密码错误", null);
                    }
                    userMap.put("Authorization", JWTUtil.signNotExpire(userMap.get("user_account").toString(), userMap.get("user_password").toString()));
                    userMap.put("bindingWxInfo", userService.myBindWx(userMap));
                    code = Constants.CODE_SUCCESS;
                    message = "账户登录成功";
                    Map<String,String> map = new HashMap<>();
                    map.put("user_account",userMap.get("user_account").toString());
                    Map<String,String> userInfo = userDao.getUser(map);
                    try {
                        this.sendMQMessage(userInfo.get("id"));
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                    resultObj.put("data", userMap);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            code = Constants.CODE_ERROR;
            message = "登录失败";
            logger.error(e.toString(), e);
        } finally {
            resultObj.put("code", code);
            resultObj.put("message", message);
            logAfter(logger);
        }
        return resultObj;
    }

    private String secretMobilePhone(String mobilePhone){
        char[] m = mobilePhone.toCharArray();
        for (int i = 0; i < m.length; i++) {
            if (i > 2 && i < 7) {
                m[i] = '*';
            }
        }
        return String.valueOf(m);
    }

    public void sendMQMessage(String userId) {
        String message = "{\"type\" : 1}";  //  type=1 App单方登录：强制退出登录
        // System.out.println("生产者产生的消息: " + message + userId);

        // routingKey 为虚拟的队列名称，与前端约定一致的uuid(设置为userId)(路由器需要设置为direct定向，把消息交给符合指定routing key的队列)
        RabbitTemplate rabbitTemplateForLogin = rmqlc.rabbitTemplateForLogin();
        rabbitTemplateForLogin.convertAndSend("amq.direct", userId, message);
    }

    private Map<String, Object> wrapResultMap (WxUserInfo wxUserInfo, String mobileAccount){
        Map<String, Object> userMap = userService.getUserInfoByAccount(mobileAccount);
        // 生成JWTtoken
        userMap.put("Authorization", JWTUtil.signNotExpire(wxUserInfo.getMobile_phone(), MD5.md5("123456")));
        // resultMap.put("wxUserInfo", wxUserInfo);
        // 绑定信息
        User user = userService.getUserByAccount(wxUserInfo.getMobile_phone());
        userMap.put("bindingWxInfo", userService.myBindWx(user));
        return userMap;
    }

    @PostMapping("modifyPassword")
    public ResponseBean modifyPassword(@RequestBody String str, HttpServletRequest request) throws MyException{
        Map reqMap = JSONObject.parseObject(str, Map.class);
        if (reqMap.get("mobile_phone") == null || StringUtils.isBlank(reqMap.get("mobile_phone").toString())) {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "请输入手机号", false);
        }
        if (reqMap.get("securityCode") == null || StringUtils.isBlank(reqMap.get("securityCode").toString())) {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "非安全操作", false);
        }
        if (reqMap.get("user_password") == null || StringUtils.isBlank(reqMap.get("user_password").toString())) {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "请输入密码", false);
        }
        String phoneNum = reqMap.get("mobile_phone").toString();
        String securityCode = reqMap.get("securityCode").toString();
        String password = reqMap.get("user_password").toString();

        Object cachesSecurityCodeObj = redisUtil.get(phoneNum + "securityCode");
        if (cachesSecurityCodeObj == null || !cachesSecurityCodeObj.toString().equals(securityCode)) {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "非安全操作", false);
        }
        //reqMap.put("user_password", MD5.md5(password));
        //userService.update(reqMap);
        reqMap.put("user_password", MD5.md5(password));
        reqMap.put("user_account", phoneNum);
        userService.updatePassWord(reqMap);
        return new ResponseBean(Constants.CODE_SUCCESS, "修改成功", true);
    }

    @PostMapping("operationLog")
    public ResponseBean operationLog(@RequestBody Map<String, Object> operationLog,HttpServletRequest request) throws MyException {
        operationLog.put("s_id",getCurrentUser(request).getS_id());
        operationLog.put("user_id",getCurrentUser(request).getId());
        operationLog.put("user_name",getCurrentUser(request).getUser_name());
        Map<String, Object> serverMap = userDao.getServerInfoBySId(operationLog);
        operationLog.put("s_name", Orgin.getString(serverMap, "user_name"));
        if (Orgin.getString(operationLog, "location").isEmpty()){
            operationLog.put("city","");
            operationLog.put("province","");
            operationLog.put("district","");
        }else {
            String[] locations = Orgin.getString(operationLog, "location").split(",");
            if (locations.length == 0) {

                operationLog.put("city","");
                operationLog.put("province","");
                operationLog.put("district","");
            }else {

                JSONObject region = addressGEOUtil.getRegion(locations[0], locations[1]);
                operationLog.put("city",region.getString("city"));
                operationLog.put("province",region.getString("province"));
                operationLog.put("district",region.getString("district"));
            }
        }
        rabbitMQCustomer.operationLoginMq(operationLog);
        return new ResponseBean(Constants.CODE_SUCCESS, "成功", true);
    }

    /**
     * 根据用户的UserAccount获取MD5加密过后的密码
     * @param reqMap
     * @return
     */
    @PostMapping("getPasswordByUserAccount")
    public ResponseBean getPasswordByUserAccount(@RequestBody Map<String, Object> reqMap) {
        String password = userDao.getPasswordByUserAccount(reqMap);

        return new ResponseBean(Constants.CODE_SUCCESS, "成功", password);
    }

    /**
     * 一键登录，获取登录成功后解密过后的电话号码
     */
    @PostMapping("/getPhoneByJVerify")
    private ResponseBean getPhoneByJVerify(@RequestBody Map<String, Object> reqMap) {
        String loginToken = reqMap.get("loginToken").toString();

        JSONObject param = new JSONObject();
        param.put("loginToken", loginToken);
        String result = HttpRequest.post("https://api.verification.jpush.cn/v1/web/loginTokenVerify")
                .basicAuth(jpushConfig.getAppKey(), jpushConfig.getMasterSecret())
                .body(param.toString())
                .timeout(20000)
                .execute().body();

        JSONObject jsonObject = JSON.parseObject(result);

        // 加密后的电话号码（RSA加密）
        String phoneToken = jsonObject.getString("phone");

        // 返回解密后的电话号码（通过私钥解密）
        if (phoneToken != null) {
            RSA rsa = new RSA(jVerifyConfig.getPrivateKey(),jVerifyConfig.getPublicKey());
            byte[] decrypt = rsa.decrypt(phoneToken, KeyType.PrivateKey);

            String phoneNumber = StrUtil.str(decrypt, CharsetUtil.CHARSET_UTF_8);
            logger.info(phoneNumber);

            return new ResponseBean(Constants.CODE_SUCCESS, "成功获取手机号码", phoneNumber);
        } else {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "无法获取手机号码", null);
        }
    }
}